package com.sychip.fhc.app.drawer.screen

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.BluetoothSearching
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.contentColorFor
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.base.noStyle
import com.fhc.base.parseBold
import com.fhc.ble.ScannerScreen
import com.fhc.ble.ScannerViewModel
import com.fhc.ble.common.DeviceActions
import com.fhc.ble.common.DeviceServices
import com.fhc.view.list.ClickableListItem
import com.fhc.view.utils.Hint
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.source.dto.BleDeviceDto
import com.sychip.fhc.app.drawer.screen.BleScanViewModel.UiTestState
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.util.rssiColor
import com.sychip.fhc.app.wsn.nav.PostToWsnDetail
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.launch
import no.nordicsemi.kotlin.ble.client.android.Peripheral
import no.nordicsemi.kotlin.ble.core.BondState
import no.nordicsemi.kotlin.ble.core.ConnectionState
import timber.log.Timber
import kotlin.uuid.ExperimentalUuidApi


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BleScanScreen(viewModel: BleScanViewModel = hiltViewModel(), onNavigationClick: () -> Unit ={}) {
    val uiTestState by viewModel.testFlow.collectAsStateWithLifecycle()
    val pullRefreshState = rememberPullToRefreshState()
    val scope =  rememberCoroutineScope()

    val vmBleScan = hiltViewModel<ScannerViewModel>()
    val isScanning by vmBleScan.isScanning.collectAsStateWithLifecycle()
    Scaffold(
        topBar = {
            FhcTopAppBar(
                title =  R.string.app_name,
                navigationIcon = {
                    IconButton(onClick = onNavigationClick) {
                        Icon(Icons.Filled.Menu, null)
                    }
                },
                actions ={
                    IconButton(onClick = {
                        if (!isScanning)
                            vmBleScan.onScanRequested()
                        else
                            vmBleScan.onStopScanRequested()
                    }) {
//                        val infiniteTransition = rememberInfiniteTransition()
//                        val rotation by infiniteTransition.animateFloat(
//                            initialValue = 0f,
//                            targetValue = 360f,
//                            animationSpec = infiniteRepeatable(
//                                animation = tween(1000, easing = LinearEasing),
//                                repeatMode = RepeatMode.Restart
//                            ))
//                        Icon(Icons.Filled.Refresh, null, modifier = Modifier
//                            .rotate(rotation)
//                        )
                        if (isScanning)
                            CircularProgressIndicator(
                                modifier = Modifier.size(28.dp).padding(4.dp),
                                color = colorScheme.onPrimary,
                                strokeWidth = 3.dp
                            )
                        else
                            Icon(Icons.Filled.Search, null)
                    }
                }
            )
        },
    ) { innerPadding ->
       PullToRefreshBox(
            modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxSize(),
            isRefreshing = uiTestState is UiTestState.Loading,
            onRefresh = {
                viewModel.reloadTestData()
                scope.launch {
                    pullRefreshState.animateToHidden()
                }
            },
            state = pullRefreshState,
            content = {
                ScannerScreen( devicesView = { devices ->
                    viewModel.setScannedPeripheral(devices)
                    BleDeviceList()
                })
            }
        )
    }
}



@Preview(showBackground = true)
@Composable
fun BleDeviceEmptyView( modifier : Modifier = Modifier, state: UiTestState = UiTestState.Loading, onRefresh: () -> Unit = {}) {
    Box(modifier = modifier.fillMaxSize(),
        contentAlignment = Alignment.Center){
        Column(
            modifier = modifier.align(Alignment.Center),
            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {

            Image(
                painter = rememberVectorPainter(image = Icons.AutoMirrored.Filled.BluetoothSearching),
                contentDescription = null,
                modifier = Modifier.size(80.dp),
                colorFilter = ColorFilter.tint(colorScheme.onBackground.copy(alpha = 0.6f)),
            )
            Text(text = stringResource(id = R.string.wsn_no_device_data_title), color  =colorScheme.primary, fontWeight = FontWeight.ExtraBold)
            Hint(text = stringResource(id = R.string.wsn_no_device_data_info).noStyle(), textAlign = TextAlign.Center)
            when (state) {
                is UiTestState.Loading ->  {  }
                is UiTestState.Success -> {
                    if (state.data.isEmpty()) {
                        Hint(text = "state.data.isEmpty()".parseBold(), textAlign = TextAlign.Center)
                        Button(onClick = {
                            onRefresh()
                            Timber.i("   >>>>>  Button   onClick")
                        }) {
                            Text(text = "Success isEmpty --"+stringResource(id = R.string.refresh))
                        }
                    }
                }
                is UiTestState.Error -> {
                    Hint(text = stringResource(id = com.fhc.ble.R.string.no_device_guide_info).parseBold(), textAlign = TextAlign.Center)
                    Button(onClick = {
                        onRefresh()
                        Timber.i("   >>>>>  Button   onClick")
                    }) {
                        Text(text = "Error --"+stringResource(id = com.fhc.ble.R.string.scanner_error))
                    }
                }
                is UiTestState.Null -> {
                    Hint(text = stringResource(id = com.fhc.ble.R.string.no_device_guide_info).parseBold(), textAlign = TextAlign.Center)
                    Button(onClick = {
                        onRefresh()
                        Timber.i("   >>>>>  Button   onClick")
                    }) {
                        Text(text = "Null --"+stringResource(id = R.string.refresh))
                    }
                }
            }
        }
    }

}


@Composable
private fun BleDeviceList() {
    val vm = hiltViewModel<BleScanViewModel>()
    val devices by vm.bleDevices.collectAsStateWithLifecycle()
    LazyColumn(
        modifier = Modifier,
        verticalArrangement = Arrangement.spacedBy(4.dp),
        contentPadding = PaddingValues(0.dp),
    ) {
        items(devices) { device ->
            ClickableListItem(
                item = device,
                itemView={
                    BleDeviceItem( device = device )
                },
                onClick = {
                    vm.connect(ble = device, autoConnect = false)
                }
            )

        }
    }
}


@Composable
private fun BleDeviceItem(
    modifier: Modifier = Modifier,
    device: BleDeviceDto
) {
    Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
        Icon(
            imageVector = Icons.AutoMirrored.Filled.BluetoothSearching,
            contentDescription = "Icon",
            tint = Color.Blue
        )
        Spacer(modifier = Modifier.width(16.dp))
        Column(
            modifier = Modifier.fillMaxWidth().weight(1f)
        ) {
            Text( text = device.name,  color = colorScheme.onPrimaryContainer, style = MaterialTheme.typography.titleMedium )
            Spacer(modifier = Modifier.height(8.dp))
            Text( text = device.mac,  color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),  style = MaterialTheme.typography.bodyMedium )
        }
        Text( text = "${device.rssi}",  color = colorScheme.onPrimaryContainer, style = MaterialTheme.typography.titleMedium )
    }
}